// ajax
function ajax(Data) {
  let xhr = new XMLHttpRequest();
  let url = "http://8.134.194.191:9300/api/v1/cap/register";
  let method = "POST";
  xhr.open(method, url);
  /* 设置参数格式 */
  //   xhr.setRequestHeader("Content-Type", "multipart/form-data");
  /* 设置具体的参数 */
  let data = Data;
  // 正常对象格式转成json格式
  xhr.send(data);

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        let res = JSON.parse(xhr.responseText);
        console.log(res);
        render(res);
      }
    }
  };
}

// 提交后执行函数
function render(res) {
  if (res.success) {
    document.getElementById("contact_form").reset();
    handleDelete();
    window.alert("提交成功");
  } else {
    document.getElementById("contact_form").reset();
    handleDelete();
    window.alert("提交失败");
  }
}

// 提交按钮
document
  .getElementById("contact_form")
  .addEventListener("submit", function (event) {
    event.preventDefault(); // 阻止表单默认提交行为
    // 获取表单数据
    let formData = new FormData(document.getElementById("contact_form"));
    
    if (fileInput.files.length === 0) {
      formData.delete("attachment");
    }
    ajax(formData);
  });


// 添加点击删除事件
function handleDelete() {
  fileInput.value = ""; // 清除文件输入框中的值
  fileNameDisplay.textContent = "";
}

// 上传显示文件名称
var fileInput = document.getElementById("fileInput");
const fileNameDisplay = document.getElementById("fileNameDisplay");

fileInput.addEventListener("change", function () {
  const files = fileInput.files;
  if (files.length > 0) {
    const file = files[0];
    const fileName = file.name;
    const deleteIcon = '<i class="fa fa-times-circle delete-icon"></i>';
    fileNameDisplay.innerHTML = "文件名: " + fileName + deleteIcon;

    const deleteButton = fileNameDisplay.querySelector(".delete-icon");
    deleteButton.addEventListener("click", function () {
      fileInput.value = ""; // 清除文件输入框中的值
      fileNameDisplay.textContent = "";
    });
  } else {
    fileNameDisplay.textContent = "";
  }
});


// 登录按钮
let btn = document.querySelector('.donate-btn-header')
btn.addEventListener("click",function(){
  // console.log("=========");
  window.location.href = 'https://www.a100-cn.com/mall/'
})